package com.jyxd.web.util;

import java.io.*;
import java.math.BigInteger;
import java.nio.charset.StandardCharsets;

import static java.lang.Double.parseDouble;

/**
 * 删除hl7中的头和尾
 * 通常用於表示開始塊的字符是 VT（垂直製表符），即 ASCII 11。FS（文件分隔符）、ASCII 28 用於表示結束塊，使用 CR（ASCII 13）用於回車。
 * 将字节数组转成16进制字符串，去除头尾，在转回数组转成字符串
 */
public class ByteUtils {

    /**
     * 在socket中调用此方法
     * hl7去除头和尾的方法
     */
    public static String removeStr(byte[] bytes) {
        String oldstr = new String(bytes, StandardCharsets.UTF_8);
        //字节数组转16进制去除头和尾再转成字符串
        String str16 = bytesToHex(bytes);
        //回车转成字符串是hexStr2Str是unicode编码 需要正常字符串
        byte[] newBytes = hexStringToBytes(str16);
        String newStr = new String(newBytes, StandardCharsets.UTF_8);
        return newStr;
    }

    /**
     * 16进制直接转换成为字符串(无需Unicode解码)
     *
     * @param hexStr
     * @return
     */
    public static String hexStr2Str(String hexStr) {
        String str = "0123456789ABCDEF";
        char[] hexs = hexStr.toCharArray();
        byte[] bytes = new byte[hexStr.length() / 2];
        int n;
        for (int i = 0; i < bytes.length; i++) {
            n = str.indexOf(hexs[2 * i]) * 16;
            n += str.indexOf(hexs[2 * i + 1]);
            bytes[i] = (byte) (n & 0xff);
        }
        return new String(bytes);
    }

    /**
     * 字符串转换成为16进制(无需Unicode编码)
     *
     * @param str
     * @return
     */
    public static String str2HexStr(String str) {
        char[] chars = "0123456789ABCDEF".toCharArray();
        StringBuilder sb = new StringBuilder("");
        byte[] bs = str.getBytes();
        int bit;
        for (int i = 0; i < bs.length; i++) {

            bit = (bs[i] & 0x0f0) >> 4;
            sb.append(chars[bit]);
            bit = bs[i] & 0x0f;
            System.out.println(chars[(bs[i] & 0x0f0) >> 4] + "" + chars[bs[i] & 0x0f] + "--666");
            sb.append(chars[bit]);
            // sb.append(' ');
        }
        return sb.toString().trim();
    }

    /**
     * 字节数组转16进制  头对应16进制的0b   尾对应16进制的1c，去头和尾
     *
     * @param bytes 需要转换的byte数组
     * @return 转换后的Hex字符串
     */
    public static String bytesToHex(byte[] bytes) {
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < bytes.length; i++) {
            String hex = Integer.toHexString(bytes[i] & 0xFF);
            if (hex.length() < 2) {
                hex = '0' + hex;
            }
            //除去头和尾
            if ("0b".equals(hex) || "1c".equals(hex)) {

            } else {
                sb.append(hex);
            }

        }
        return sb.toString();
    }

    /**
     * 字节数组转16进制  头对应16进制的0b   尾对应16进制的1c
     *
     * @param bytes 需要转换的byte数组
     * @return 转换后的Hex字符串
     */
    public static String bytesToHexData(byte[] bytes) {
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < bytes.length; i++) {
            String hex = Integer.toHexString(bytes[i] & 0xFF);
            if (hex.length() < 2) {
                hex = '0' + hex;
            }
            sb.append(hex);
        }
        return sb.toString();
    }


    /**
     * 16进制字符串 转回byte数组
     *
     * @param hexString
     * @return
     */
    public static byte[] hexStringToBytes(String hexString) {
        if (hexString == null || hexString.equals("")) {
            return null;
        }
        hexString = hexString.toUpperCase();
        int length = hexString.length() / 2;
        char[] hexChars = hexString.toCharArray();
        byte[] d = new byte[length];
        for (int i = 0; i < length; i++) {
            int pos = i * 2;
            d[i] = (byte) (charToByte(hexChars[pos]) << 4 | charToByte(hexChars[pos + 1]));
        }
        return d;
    }

    public static byte charToByte(char c) {
        return (byte) "0123456789ABCDEF".indexOf(c);
    }

    /**
     * 将字节写入到文本文件
     *
     * @param fname
     * @param msg
     * @return
     */
    public static boolean save2File(String fname, byte[] msg) {
        OutputStream fos = null;
        try {
            File file = new File(fname);
            File parent = file.getParentFile();
            boolean bool;
            if ((!parent.exists()) &&
                    (!parent.mkdirs())) {
                return false;
            }
            fos = new FileOutputStream(file);
            fos.write(msg);
            fos.flush();
            return true;
        } catch (FileNotFoundException e) {
            return false;
        } catch (IOException e) {
            File parent;
            return false;
        } finally {
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException e) {
                }
            }
        }
    }

    /**
     * 将字节写入到文本文件
     *
     * @param fileName
     * @param msg
     * @return
     */
    public static boolean saveStrFile(String fileName, String msg) {
        FileWriter fwriter = null;
        try {
            fwriter = new FileWriter(fileName);
            fwriter.write(msg);
        } catch (IOException ex) {
            ex.printStackTrace();
        } finally {
            try {
                fwriter.flush();
                fwriter.close();
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
        return true;
    }

    /**
     * 将byte[]转为各种进制的字符串
     *
     * @param bytes byte[]
     * @param radix 基数可以转换进制的范围，从Character.MIN_RADIX到Character.MAX_RADIX，超出范围后变为10进制
     * @return 转换后的字符串
     */
    public static String binary(byte[] bytes, int radix) {
        return new BigInteger(1, bytes).toString(radix);// 这里的1代表正数
    }

    public static void saveTwoFile(String fileName, byte[] bytes) {
        try {
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            DataOutputStream os = new DataOutputStream(
                    new BufferedOutputStream(new FileOutputStream(
                            fileName)));
            os.write(bytes);
            os.flush();
            os.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

   /* public static void main(String[] args) {
        byte[] bytes = new byte[3];
        bytes[0] = 89;
        bytes[1] = 89;
        bytes[2] = 98;
        saveStrFile("D:\\idea_project\\jyxd-gitee\\target\\a", binary(bytes,2));
    }*/

    /**
     * 提前字符串中的所有值并且相加
     *
     * @param content
     * @return
     */
    public static double getDoubleTotal(String content) {
        if (content == null) return 0.0;
        byte[] arr = content.getBytes();
        byte[] tmp = new byte[30];
        for (int k = 0; k < 30; k++) tmp[k] = 0;
        double total = 0;

        int i, j, n = 0, p = 0;
        for (i = j = 0; i < arr.length && j < 30; i++) {
            byte ch = (byte) (arr[i] & 0xff);
            if (ch >= '0' && ch <= '9') {
                n++;
                if (n == 1) {
                    if (i > 0 && (byte) (arr[i - 1] & 0xff) == '.') {
                        tmp[j++] = '0';
                        tmp[j++] = '.';
                        p = 1;
                    }
                }
                tmp[j++] = ch;

                if (i == arr.length - 1) {
                    total += parseDouble(new String(tmp));
                }
            } else if (n > 0 && ch == '.' && p == 0) {
                if (i == arr.length - 1) {
                    total += parseDouble(new String(tmp));
                }
                tmp[j++] = arr[i];
                p = 1;
            } else if (n > 0) {
                if (tmp[j - 1] == '.') tmp[j++] = '0';
                total += parseDouble(new String(tmp));
                n = 0;
                j = 0;
                p = 0;
                for (int k = 0; k < 30; k++) tmp[k] = 0;
            }
        }
        return total;
    }
}
